/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
public class Introspection {
    // Dynamically and recursively retrieve a property value from an object
    // A FilterProperty can be like "music.artist.name" 
    //   where music is a Music object, artist is an Artist object and name is the String field we want to retrieve
    public static String getFieldFromObject(Object object, String filterProperty) {
        //System.out.println("PROPERTY TO FILTER => " + filterProperty);
        try {
            // Test if the property value we want to retrieve is in a composed object like for example "music.artist.name"
            if (!filterProperty.contains(".")) {
                // If not, directly retrieve the value
                //System.out.println("cas 1 => " + object.getClass());
                String fieldValue = String.valueOf(new PropertyDescriptor(filterProperty, object.getClass()).getReadMethod().invoke(object));
                return fieldValue;


            } else {
                // Retrieve the value recursively
                //System.out.println("cas 2 => " + object.getClass());
                String[] properties = filterProperty.split("\\.", 2);
                Object field = new PropertyDescriptor(properties[0], object.getClass()).getReadMethod().invoke(object);
                return getFieldFromObject(field, properties[1]);
            }


        } catch (IllegalAccessException ex) {
        } catch (IllegalArgumentException ex) {
        } catch (InvocationTargetException ex) {
        } catch (IntrospectionException ex) {
        }

        return "";
    }
}
